

using System;
using System.Resources;
using System.Drawing;
using System.Collections;
using System.Reflection;
using System.ComponentModel;
using System.Text;
using System.IO;
using Microsoft.BizTalk.Message.Interop;
using Microsoft.BizTalk.Component.Interop;

namespace BTSPracCourse.PipeLines.PipeLineComponents
{
    [ComponentCategory(CategoryTypes.CATID_PipelineComponent)]
    [ComponentCategory(CategoryTypes.CATID_Any)]
    [ComponentCategory(CategoryTypes.CATID_Decoder)]
    [System.Runtime.InteropServices.Guid("5596B817-E34C-4005-AC86-0E733FFB0EEC")]
    public class GreenShieldCleanComponent : BaseCustomTypeDescriptor,
        IBaseComponent,
        Microsoft.BizTalk.Component.Interop.IComponent,
        Microsoft.BizTalk.Component.Interop.IPersistPropertyBag,
        IComponentUI
    {
        
        static	ResourceManager resManager = new ResourceManager("BTSPracCourse.Pipeline.PipeLineComponents", Assembly.GetExecutingAssembly());
        public GreenShieldCleanComponent()
            : base(resManager)
        {
        }

        #region IComponentUI Members
        // <summary>
        /// Component icon to use in BizTalk Editor.
        /// </summary>
        [Browsable(false)]
        public IntPtr Icon
        {
            get { return IntPtr.Zero; }
        }

        // <summary>
        /// The Validate method is called by the BizTalk Editor during the build 
        /// of a BizTalk project.
        /// </summary>
        /// <param name="obj">Project system.</param>
        /// <returns>
        /// A list of error and/or warning messages encounter during validation
        /// of this component.
        /// </returns>
        public IEnumerator Validate(object projectSystem)
        {
            return null;
        }

        #endregion

        #region IPersistPropertyBag Members

        public void GetClassID(out Guid classID)
        {
            classID = new System.Guid(GreenShieldCleanComponent.compGUID);
        }

        public void InitNew()
        {
            
        }

        public void Load(IPropertyBag propertyBag, int errorLog)
        {
            string val = (string)ReadPropertyBag(propertyBag, "RecLength");
            if (val != null) recLength = val;
        }

        public void Save(IPropertyBag propertyBag, bool clearDirty, bool saveAllProperties)
        {
            object val = (object)recLength;
            WritePropertyBag(propertyBag, "RecLength", val);   
        }
        /// <summary>
		/// Reads property value from property bag.
		/// </summary>
		/// <param name="pb">Property bag.</param>
		/// <param name="propName">Name of property.</param>
		/// <returns>Value of the property.</returns>
		private static object ReadPropertyBag(Microsoft.BizTalk.Component.Interop.IPropertyBag pb, string propName)
		{
			object val = null;
			try
			{
				pb.Read(propName,out val,0);
			}

			catch(System.ArgumentException)
			{
				return val;
			}
			catch(Exception ex)
			{
				throw new ApplicationException( ex.Message);
			}
			return val;
		}

		private static void WritePropertyBag(Microsoft.BizTalk.Component.Interop.IPropertyBag pb, string propName, object val)
		{
			try
			{
				pb.Write(propName, ref val);
			}
			catch(Exception ex)
			{
				throw new ApplicationException( ex.Message);
			}
		}
     
		#endregion



        private string recLength = "187";

        /// <summary>
        /// Location of Xsl transform file.
        /// </summary>
        public string RecordLength
        {
            get { return recLength; }
            set { recLength = value; }
        }

        #region IComponent Members
        /// <summary>
        /// Implements IComponent.Execute method.
        /// </summary>
        /// <param name="pc">Pipeline context</param>
        /// <param name="inmsg">Input message.</param>
        /// <returns>Processed input message with appended or prepended data.</returns>
        /// <remarks>
        /// IComponent.Execute method is used to initiate
        /// the processing of the message in pipeline component.
        /// </remarks>
        public IBaseMessage Execute(IPipelineContext pContext, IBaseMessage pInMsg)
        {
            IBaseMessagePart bodyPart = pInMsg.BodyPart;
            int recordlength = int.Parse(recLength);
            // remove the header, the trailer and the line feed and new line characters from the stream 
            if (bodyPart != null)
            {
                MemoryStream ms = new MemoryStream();
                Stream srcs = bodyPart.GetOriginalDataStream();
                StreamReader tr = new StreamReader(srcs);
                StreamWriter tw = new StreamWriter(ms);
                string str = string.Empty;
                while (!tr.EndOfStream)
                {
                    str = tr.ReadLine();
                    System.Diagnostics.Debug.WriteLine(str);
                    int spacesneeded = 762 - str.Length;
                    if (spacesneeded > 0)
                    {
                        str += new string(' ', spacesneeded);
                    }
                    tw.WriteLine(str);
                }
                tw.Flush();
                ms.Seek(0, SeekOrigin.Begin);
                bodyPart.Data = ms;
                pContext.ResourceTracker.AddResource(ms);

            }
            return pInMsg;
        }

        #endregion

        #region IBaseComponent Members
        /// <summary>
        /// Description of the component.
        /// </summary>
        [Browsable(false)]
        public string Description
        {
            get { return GreenShieldCleanComponent.compDescp; }
        }
        /// <summary>
        /// Name of the component.
        /// </summary>
        [Browsable(false)]
        public string Name
        {
            get { return GreenShieldCleanComponent.compName; }
        }
        /// <summary>
        /// Version of the component.
        /// </summary>
        [Browsable(false)]
        public string Version
        {
            get { return GreenShieldCleanComponent.compVersion; }
        }

        #endregion

        #region Constants
        private static readonly string compName = "GreenShield Cleaner Component";
        private static readonly string compDescp = "BizTalk 2006 Pipeline component";
        private static readonly string compVersion = "1.0.0.0";
        private static readonly string compGUID = "5596B817-E34C-4005-AC86-0E733FFB0EEC";

        #endregion

    }

    #region BaseCustomTypeDescriptor
    /// <summary>
    /// Custom type description for pipeline component properties
    /// </summary>
    public class BaseCustomTypeDescriptor : ICustomTypeDescriptor
    {
        private ResourceManager resourceManager;

        public BaseCustomTypeDescriptor(ResourceManager resourceManager)
        {
            this.resourceManager = resourceManager;
        }

        public AttributeCollection GetAttributes()
        {
            return new AttributeCollection(null);
        }
        public virtual string GetClassName()
        {
            return null;
        }
        public virtual string GetComponentName()
        {
            return null;
        }
        public TypeConverter GetConverter()
        {
            return null;
        }
        public EventDescriptor GetDefaultEvent()
        {
            return null;
        }
        public PropertyDescriptor GetDefaultProperty()
        {
            return null;
        }
        public object GetEditor(Type editorBaseType)
        {
            return null;
        }
        public EventDescriptorCollection GetEvents()
        {
            return EventDescriptorCollection.Empty;
        }
        public EventDescriptorCollection GetEvents(Attribute[] filter)
        {
            return EventDescriptorCollection.Empty;
        }

        public virtual PropertyDescriptorCollection GetProperties()
        {
            PropertyDescriptorCollection srcProperties = TypeDescriptor.GetProperties(this.GetType());

            return srcProperties;
        }

        public virtual PropertyDescriptorCollection GetProperties(Attribute[] filter)
        {
            return this.GetProperties();
        }

        public object GetPropertyOwner(PropertyDescriptor pd)
        {
            return this;
        }
    }
    #endregion
	
}
